<template>
  <el-dropdown 
    trigger="click" 
    placement="bottom-end"
    @visible-change="handleDropdownVisibleChange"
  >
    <div class="notification-trigger">
      <el-badge :value="unreadCount" :hidden="unreadCount === 0" :max="99">
        <el-button type="text" size="large" class="notification-btn">
          <el-icon><Bell /></el-icon>
        </el-button>
      </el-badge>
    </div>
    
    <template #dropdown>
      <el-dropdown-menu class="notification-dropdown">
        <div class="notification-header">
          <span class="title">通知中心</span>
          <div class="actions">
            <el-button 
              type="text" 
              size="small" 
              @click="markAllAsRead"
              :disabled="unreadCount === 0"
            >
              全部已读
            </el-button>
            <el-button 
              type="text" 
              size="small" 
              @click="goToNotificationCenter"
            >
              查看全部
            </el-button>
          </div>
        </div>
        
        <div class="notification-content" v-loading="loading">
          <div v-if="notifications.length === 0" class="empty-state">
            <el-icon class="empty-icon"><Bell /></el-icon>
            <p>暂无通知</p>
          </div>
          
          <div v-else class="notification-list">
            <div
              v-for="notification in notifications"
              :key="notification.id"
              class="notification-item"
              :class="{ 'unread': !notification.is_read }"
              @click="handleNotificationClick(notification)"
            >
              <div class="notification-icon">
                <el-icon :color="getPriorityColor(notification.priority)">
                  <component :is="getNotificationTypeIcon(notification.notification_type)" />
                </el-icon>
              </div>
              
              <div class="notification-body">
                <div class="notification-title">{{ notification.title }}</div>
                <div class="notification-content-text">{{ notification.content }}</div>
                <div class="notification-meta">
                  <span class="sender">{{ notification.sender_name }}</span>
                  <span class="time">{{ formatTime(notification.created_at) }}</span>
                </div>
              </div>
              
              <div class="notification-status">
                <el-tag 
                  v-if="!notification.is_read" 
                  type="danger" 
                  size="small"
                  effect="plain"
                >
                  未读
                </el-tag>
              </div>
            </div>
          </div>
        </div>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { notificationApi, type Notification, getNotificationTypeIcon, getPriorityColor } from '@/api/notifications'
import { formatTime } from '@/utils/format'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const unreadCount = ref(0)
const notifications = ref<Notification[]>([])

// 定时器
let refreshTimer: NodeJS.Timeout | null = null

// 获取未读通知数量
const fetchUnreadCount = async () => {
  try {
    const response = await notificationApi.getUnreadCount()
    const data = response.data || response
    unreadCount.value = data.count
  } catch (error) {
    console.error('获取未读通知数量失败:', error)
  }
}

// 获取最新通知列表（前5条）
const fetchRecentNotifications = async () => {
  loading.value = true
  try {
    const response = await notificationApi.getNotificationList({
      page: 1,
      page_size: 5
    })
    const data = response.data || response
    notifications.value = data.results || []
  } catch (error) {
    console.error('获取通知列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 标记所有通知为已读
const markAllAsRead = async () => {
  try {
    await notificationApi.markAllAsRead()
    ElMessage.success('已标记所有通知为已读')
    
    // 更新本地状态
    notifications.value.forEach(notification => {
      notification.is_read = true
    })
    unreadCount.value = 0
  } catch (error) {
    ElMessage.error('标记失败')
  }
}

// 处理通知点击
const handleNotificationClick = async (notification: Notification) => {
  // 如果未读，标记为已读
  if (!notification.is_read) {
    try {
      await notificationApi.markAsRead(notification.id)
      notification.is_read = true
      unreadCount.value = Math.max(0, unreadCount.value - 1)
    } catch (error) {
      console.error('标记已读失败:', error)
    }
  }
  
  // 跳转到通知详情或相关页面
  router.push('/notifications')
}

// 跳转到通知中心
const goToNotificationCenter = () => {
  router.push('/notifications')
}

// 处理下拉菜单显示/隐藏
const handleDropdownVisibleChange = (visible: boolean) => {
  if (visible) {
    fetchRecentNotifications()
  }
}

// 定时刷新未读数量
const startRefreshTimer = () => {
  refreshTimer = setInterval(() => {
    fetchUnreadCount()
  }, 30000) // 每30秒刷新一次
}

// 停止定时器
const stopRefreshTimer = () => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
    refreshTimer = null
  }
}

// 生命周期
onMounted(() => {
  fetchUnreadCount()
  startRefreshTimer()
})

onUnmounted(() => {
  stopRefreshTimer()
})

// 暴露方法供父组件调用
defineExpose({
  refresh: fetchUnreadCount
})
</script>

<style lang="scss" scoped>
.notification-trigger {
  .notification-btn {
    color: var(--text-color-primary);
    transition: all 0.3s ease;

    &:hover {
      color: var(--color-primary);
      background-color: var(--fill-color-light);
    }
  }
}

.notification-dropdown {
  width: 360px;
  max-height: 480px;
  padding: 0;

  .notification-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
    border-bottom: 1px solid var(--border-color-lighter);
    background: var(--fill-color-extra-light);

    .title {
      font-weight: 600;
      color: var(--text-color-primary);
    }

    .actions {
      display: flex;
      gap: 8px;

      .el-button {
        padding: 0;
        font-size: 12px;
      }
    }
  }

  .notification-content {
    max-height: 400px;
    overflow-y: auto;

    .empty-state {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 40px 20px;
      color: var(--text-color-placeholder);

      .empty-icon {
        font-size: 48px;
        margin-bottom: 12px;
        opacity: 0.5;
      }

      p {
        margin: 0;
        font-size: 14px;
      }
    }

    .notification-list {
      .notification-item {
        display: flex;
        align-items: flex-start;
        padding: 12px 16px;
        border-bottom: 1px solid var(--border-color-extra-light);
        cursor: pointer;
        transition: background-color 0.3s ease;

        &:hover {
          background-color: var(--fill-color-light);
        }

        &.unread {
          background-color: var(--color-primary-light-9);
          border-left: 3px solid var(--color-primary);
        }

        &:last-child {
          border-bottom: none;
        }

        .notification-icon {
          margin-right: 12px;
          margin-top: 2px;

          .el-icon {
            font-size: 18px;
          }
        }

        .notification-body {
          flex: 1;
          min-width: 0;

          .notification-title {
            font-weight: 500;
            color: var(--text-color-primary);
            margin-bottom: 4px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          .notification-content-text {
            font-size: 13px;
            color: var(--text-color-regular);
            line-height: 1.4;
            margin-bottom: 6px;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
          }

          .notification-meta {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 12px;
            color: var(--text-color-placeholder);

            .sender {
              font-weight: 500;
            }
          }
        }

        .notification-status {
          margin-left: 8px;
          margin-top: 2px;
        }
      }
    }
  }
}
</style>
